<template>
  <div class="L-login-container">

    <div class="L-margin-30 L-text-align-center">
      <img src="@/assets/images/BIPlogo.png">
    </div>

    <div class="L-margin-top-50">
      <van-tabs v-model:active="loginType">

        <!-- 账号登录 -->
        <van-tab title="账号登录" :name="0" class="L-margin-20">
          <van-cell-group inset style="opacity:0.7">
            <van-field v-model="username" required label="用户名" placeholder="请输入用户名" />
            <van-field type="password" v-model="password" required label="密码" placeholder="请输入密码" />
          </van-cell-group>
          <van-row justify="space-between" class="L-margin-20" style="width:80%">
            <van-checkbox icon-size="16px" shape="square" v-model="isRemember">
              <span class="L-secondary-text-color">记住密码</span>
            </van-checkbox>
            <a class="blue" @click="router.push('/forget')">忘记密码</a>
            <!-- <a class="blue" @click="router.push('/changepwd')">忘记密码</a> -->
          </van-row>
        </van-tab>

        <!-- 手机号登录 -->
        <van-tab title="手机号登录" :name="1" class="L-margin-20">
          <van-cell-group inset style="opacity:0.7">
            <van-field v-model="phone" required label="手机号" placeholder="请输入手机号" />
            <van-field v-model="sms" required center clearable label="短信验证码" placeholder="请输入短信验证码">
              <template #button>
                <van-button plain style="width:90px" size="small" @click="sendSmsCode" type="primary">
                  {{ smsText }}
                </van-button>
              </template>
            </van-field>
          </van-cell-group>

          <van-row v-show="isSended" justify="center" align="center" class="L-margin-20" style="width:90%">
            <span class="L-secondary-text-color">没有收到验证码?</span>
            <a class="blue" @click="sendSmsCode">重新发送</a>
          </van-row>
        </van-tab>
      </van-tabs>
    </div>

    <div class="L-margin-top-40 L-text-align-center">
      <van-button @click="handleLogin" type="primary" round size="large" class="L-login-btn">登录</van-button>
    </div>

  </div>
</template>

<script setup lang="ts">
import {
  showLoadingToast,
  closeToast,
  showDialog,
  showToast,
  showNotify,
} from "vant";
import { useAuthStore } from '@/stores/userInfo'
import { ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { phonelogincfg, loginbusinessphone, loginbusiness, fsyzm } from "@/request/api/login";
import { apiConfigurable } from "@/request/api/api"
import { isValidPhoneNumber } from "@/utils/func";
import * as dd from 'dingtalk-jsapi'

import { useSms } from "@/hooks/hooks";

const router = useRouter();
const route = useRoute()

const { sms, smsText, smsNum, smsTimer, smsCounter, isSended } = useSms()

let loginType = ref(0);
let phoneLogin = ref(false);

let phone = ref("");
// let sms = ref("");
// let smsText = ref("发送验证码");
// let smsNum = ref(60);
// let smsTimer = null;

let wxuserid = ref("");
let dduserid = ref(""); //钉钉userid
let wxgzuserid = ref(""); //微信公众号userid
let ykjuserid = ref("");


let isRemember = ref(false);
isRemember.value = localStorage.getItem("isRemember") === "true" ? true : false
let username = ref("");
let password = ref("");
if (isRemember.value) {

  if (JSON.parse(localStorage.getItem("jkbcrm"))) {
    const userInfo = JSON.parse(localStorage.getItem("jkbcrm"))
    username.value = userInfo.username
    password.value = userInfo.password
    // handleLogin()

  }
}



onMounted(() => {
  // getIsCanPhoneLogin();

  autoLogin()
});

const logintype = ref("")
// const corpId = ref("")

const code = ref("")
const clientId = 'dingbvhcxuz54uk2e3kn'

const corpId = route.query.corpId as string
// console.log("route.query.corpId", route.query.corpId)
// console.log("corpId", corpId)


function autoLogin() {


  let ua = window.navigator.userAgent.toLowerCase()

  if (ua.indexOf('dingtalk') !== -1) {
    logintype.value = 'dingding'
  }
  if (logintype.value === 'dingding') {
    dd.ready(() => {

      dd.requestAuthCode({
        corpId: corpId,
        clientId: clientId,
        onSuccess: function (result) {
          // console.log("onSuccess result", result)
          // 通过该免登授权码可以获取用户身份
          let data = {
            'code': result.code,
            'source': 'dingtalk',
            // 调用新版的dingding api
            'initiatorFromApp': 'true',
            'corpId': corpId
          }

          showToast("加载中...")

          apiConfigurable('/api/ssoaly', data).then(res => {
            console.log("res", res)
            console.log("res.code", res.code)
            console.log("res.data", res.data)
            if (res.code === 0) {
              router.replace("/main");

            } else {
              console.log("levy111")
              console.log("res.data.dduserid", res.data.dduserid)
              dduserid.value = res.data.dduserid//钉钉userid
              wxuserid.value = res.data.wxuserid//微信userid
            }


          })

        },
        onFail: function (err) { },
      });

    })


  }
}



//是否可以手机号码登录
function getIsCanPhoneLogin(): void {
  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });

  phonelogincfg().then((res) => {
    if (res.code === 0) {
      // phoneLogin.value = res;
    }
  })
    .finally(() => {
      closeToast();
    });
}

//发送验证码
function sendSmsCode() {
  if (phone.value === "") {
    showNotify("请输入手机号");
    return;
  }
  //   if (!isValidPhoneNumber(phone.value)) {
  //     showNotify("手机号格式不正确");
  //     return;
  //   }
  if (smsNum.value !== 60) {
    showToast("验证码发送频率过高");
    return;
  }

  const params = {
    phone: phone.value,
    smobile: phone.value,
    wxuserid: wxuserid.value,
    dduserid: dduserid.value,
    wxgzuserid: wxgzuserid.value,
    clienttype: "mobile",
  };

  showLoadingToast({
    message: "发送中...",
    forbidClick: true,
    duration: 0,
  });

  fsyzm(params).then((res) => {
    if (res.code === 0) {
      showToast("验证码已发送");
      smsCounter()//验证码读秒器

    }
  });
}






//表单检查
function checkForm() {
  if (username.value === "" && loginType.value === 0) {
    showNotify("请输入用户名");
    return false
  }
  // if (password.value === "" && loginType.value === 0) {
  //   showNotify("请输入密码");
  //   return false
  // }

  if (phone.value === "" && loginType.value === 1) {
    showNotify("请输入电话号");
    return false
  }

  if (!isValidPhoneNumber(phone.value) && loginType.value === 1) {
    showNotify("电话号格式不正确");
    return false
  }

  if (sms.value === "" && loginType.value === 1) {
    showNotify("请输入验证码");
    return false
  }
  return true
}

//登录操作
function handleLogin() {
  if (!checkForm()) {
    return
  }

  if (!ykjuserid.value) {
    ykjuserid.value = window.localStorage.getItem("ykjuserid");
  }

  window.localStorage.setItem("isRemember", `${isRemember.value}`);


  if (isRemember.value) {
    if (!username.value) {
      window.localStorage.removeItem("jkbcrm");
    } else {
      window.localStorage.setItem(
        "jkbcrm", JSON.stringify({ username: username.value, password: password.value })
      );
    }
  } else {

    window.localStorage.removeItem("jkbcrm");
  }

  if (!wxuserid.value) {
    var r = window.location.search
      .substr(1)
      .match(new RegExp("(^|&)wxuserid=([^&]*)(&|$)"));
    if (r != null) {
      wxuserid.value = unescape(r[2]);
    }
  }

  // dduserid.value = window.localStorage.getItem("dduserid");
  // if (!dduserid.value) {
  //   var d = window.location.search
  //     .substr(1)
  //     .match(new RegExp("(^|&)dduserid=([^&]*)(&|$)"));
  //   if (d != null) {
  //     dduserid.value = unescape(d[2]);
  //   }
  // }
  // if (!wxgzuserid.value) {
  //   var gz = window.location.search
  //     .substr(1)
  //     .match(new RegExp("(^|&)wxgzuserid=([^&]*)(&|$)"));
  //   if (gz != null) {
  //     wxgzuserid.value = unescape(gz[2]);
  //   }
  // }

  // if (!ykjuserid.value) {
  //   var ykj = window.location.search
  //     .substr(1)
  //     .match(new RegExp("(^|&)ykjuserid=([^&]*)(&|$)"));
  //   if (ykj != null) {
  //     ykjuserid.value = unescape(ykj[2]);
  //   }
  // }

  let data = {
    dxyzm: sms.value,
    phone: phone.value,
    smobile: phone.value,
    username: username.value,
    password: password.value,
    wxuserid: wxuserid.value,
    dduserid: dduserid.value,
    wxgzuserid: wxgzuserid.value,
    ykjuserid: ykjuserid.value,
    clienttype: "mobile",
  };
  console.log("data dduserid", dduserid.value)

  showLoadingToast({
    message: "登录中...",
    forbidClick: true,
    duration: 0,
  });

  const loginRes = loginType.value === 0 ? loginbusiness(data) : loginbusinessphone(data); //loginType 0:账号密码登录 1:手机号验证码登录
  // loginType.value === 0 ? loginbusiness(JSON.stringify(data)) : loginbusinessphone(JSON.stringify(data));

  loginRes.then((res) => {
    if (res.code === 0) {
      if (res.data.token) {
        const userStore = useAuthStore();
        userStore.setToken(res.data.token)
      }
      sessionStorage.setItem('isLogin', '1')
      sessionStorage.setItem('username', username.value)
      // const projectData = require("../project.json");
      const projectData = {
        project: "",
      };
      if (projectData.project === "chenxin/") {
        if (!password.value || password.value === "cx603367") {
          showDialog({
            title: "标题",
            message: "登陆密码为空或者为cx603367,请修改密码!",
          }).then(() => {
            router.push("/changpwd");
          });
        } else {

          router.push("/main");
        }
      } else {
        // debugger
        router.push("/main");
      }
      closeToast();
    }

  });
}
</script>

<style scoped></style>